#!/usr/bin/perl -w
# PSAP2PSAT converts PSAP data file into PSAT data file
#
# PSAP2PSAT <OPTIONS> FILEINPUT <FILEOUTPUT>
#
# Author:  Federico Milano
# Date:    25-Jun-2003
# Version: 1.0.0
#
#E-mail:    fmilano@thunderbox.uwaterloo.ca
#Web-site:  http://thunderbox.uwaterloo.ca/~fmilano

use strict;

# -----------------------------------------------------------------------
# variable declaration
# -----------------------------------------------------------------------
my $nargin = 0;
my $verbose = 0;
my $helpmsg = 0;
my ($i,$h,$k);
my $format;
my $n = 0;
my $npv = -1;
my $nsw = -1;
my $npq = -1;
my $nsh = -1;
my (@idxpv, @idxsw, @idxpq, @idxsh);
my $pbas = 100;
my $iter = 20;
my $toler = 0.0001;
my $nbus = -1;
my $nline = -1;
my $narea = -1;
my $flag_bus = 0;
my $flag_line = 0;
my $flag_area = 0;
my $flag_trsf = 0;
my $flag = 1;
my (@busidx,@bustype,@busname);
my (@ein,@ang,@pag,@prg,@qmi,@qma,@tap,@pac,@prc,@qsh,@kae,@kvb);	    
my %kvbase;
my (@busfr,@busto);
my (@rest,@reat,@susc,@tfas,@tfmi,@tfma,@phsf,@nbci,@cano,@caem,@sbas);	    
my (@areaidx,@areabus,@areaexp,@areaint,@areaname,@areaload,@arealoss);

# -----------------------------------------------------------------------
# check inputs
# -----------------------------------------------------------------------
$nargin = @ARGV;
$nargin || die "Error: No input data file.\n";
my $title1 = 'Generic PSAP Data Format File '.$ARGV[0];
my $title2 = '   ';

# -----------------------------------------------------------------------
# check options
# -----------------------------------------------------------------------
while ($ARGV[0] =~ /^-/) {
    if ($ARGV[0] =~ /v/) {$verbose = 1;}
    if ($ARGV[0] =~ /h/) {$helpmsg = 1;}
    shift(@ARGV);
    $nargin--;
    if ($nargin == 0) { 
	last;
    }
}

# -----------------------------------------------------------------------
# help (if requested)
# -----------------------------------------------------------------------
if ($helpmsg) {
    print "\nPSAP2PSAT converts PSAP/PECO data files into PSAT data files.\n\n";
    print "psap2psat <options> fileinput <fileoutput>\n";
    print "  -v   verbose\n";
    print "  -h   print this help and exit\n\n";
    print "Author:   Federico Milano\n";
    print "Date:     25-Jun-2003\n";
    print "Version:  1.0.0\n\n";
    print "E-mail:   fmilano\@thunderbox.uwaterloo.ca\n";
    print "Web-site: http://thunderbox.uwaterloo.ca/~fmilano\n";
    die "\n";
}

# -----------------------------------------------------------------------
# define output file name (if necessary)
# -----------------------------------------------------------------------
if ($nargin == 1) {
    $ARGV[1] = $ARGV[0];
    $ARGV[1] =~ s/^d*_*/d_/;
    $ARGV[1] =~ s/[^\w\.]/_/g;
    $ARGV[1] =~ s/\..+$/.m/;
} elsif ($nargin == 0) {
    die "Error: Input file name is missing.\n";
}

# -----------------------------------------------------------------------
# open input data file
# -----------------------------------------------------------------------
print "Opening PSAP file \"$ARGV[0]\"...\n";
carret();
open(IN,$ARGV[0]) || die "cannot open $ARGV[0]: $!\n";

# -----------------------------------------------------------------------
# scan input data file
# -----------------------------------------------------------------------
while (<IN>) {
    chomp;
    $n++;
    if (/^C/) { # comment 
	next;
    } elsif (/^9999/) { # reset flags
	$flag = 1;
	$flag_bus  = 0;
	$flag_line = 0;
	$flag_area = 0;
	$flag_trsf = 0;
	carret();
    } elsif (/^(001|  1)/ && $flag) { # 1th row title 
	$_ = <IN>;
	chomp;	
	#s/^0*1\s//;
	$title1 = $_;
    } elsif (/^(002|  2)/ && $flag)  { # 2nd row title 
	$_ = <IN>;
	chomp;	
	#s/^0*2\s//;
	$title2 = $_;
    } elsif (/^(011| 11)/ && $flag) { # miscellaneous data
	$_ = <IN>; 
	chomp;	
	$pbas  = assign($_,0,6,100); 
	$iter  = assign($_,9,2,20);
	$toler = assign($_,14,10,0.0001);
    } elsif (/^(005|  5)/ && $flag)  { # enforce bus data acquisition
	$flag = 0;
	$flag_bus  = 1;
	$flag_line = 0;
	$flag_area = 0;
	$flag_trsf = 0;
	print "Scanning bus data...\n";
    } elsif (/^(004|  4)/ && $flag)  { # enforce line data acquisition
	$flag = 0;
	$flag_bus  = 0;
	$flag_line = 1;
	$flag_area = 0;
	$flag_trsf = 0;
	print "Scanning line data...\n";
    } elsif (/^(015| 15)/ && $flag)  { # enforce area data acquisition
	$flag = 0;
	$flag_bus  = 0;
	$flag_line = 0;
	$flag_area = 1;
	$flag_trsf = 0;
	print "Scanning area data...\n";
    } elsif (/^(055| 55)/ && $flag) { # network link audit
        $verbose && print "Card 055: neglected.\n";
    } elsif (/^(033| 33)/ && $flag) { # run power flow
        $verbose && print "Card 033: neglected.\n";
    } elsif (/^(077| 77)/ && $flag) { # run power flow
        $verbose && print "Card 077: neglected.\n";
    } elsif ($flag_bus) { # evaluate bus data row
	$_ = $_ . " " x 20;
	$nbus++;
	$busidx[$nbus]  = assign($_,0,4,1);
	$bustype[$nbus] = assign($_,7,1,0);
	if ($bustype[$nbus] == 1) {
	    $npv++;
	    $idxpv[$npv] = $nbus;
	} elsif ($bustype[$nbus] == 2) {
	    $nsw++;
	    $idxsw[$nsw] = $nbus;
	}
	$busname[$nbus] = deblank(substr($_,9,12));
	$ein[$nbus] = assign($_,22,5,1);
        if ($ein[$nbus] > 100) {$ein[$nbus] = $ein[$nbus]/1000;}
	$ang[$nbus] = 3.141592654*assign($_,26,4,0)/180;	    
	$pag[$nbus] = assign($_,30,5,0)/$pbas;
	$prg[$nbus] = assign($_,35,5,0)/$pbas;
	$qmi[$nbus] = assign($_,40,5,0)/$pbas;
	$qma[$nbus] = assign($_,45,5,0)/$pbas;
	$tap[$nbus] = assign($_,50,5,0);
	$pac[$nbus] = assign($_,55,5,0)/$pbas;
	$prc[$nbus] = assign($_,60,5,0)/$pbas;
	if ($pac[$nbus] || $prc[$nbus]) {
	    $npq++;
	    $idxpq[$npq] = $nbus;
	}
	$qsh[$nbus] = assign($_,66,5,0)/$pbas/$ein[$nbus]/$ein[$nbus];	    
	if ($qsh[$nbus]) {
	    $nsh++;
	    $idxsh[$nsh] = $nbus;
	}
	$kae[$nbus] = assign($_,70,2,1);	    
	$kvb[$nbus] = assign($_,72,4,1.00);
	$kvbase{$busidx[$nbus]} = $kvb[$nbus];
	$verbose && printf("Found Bus  %4d:  $busname[$nbus]\n",$nbus+1);
    } elsif ($flag_trsf) { # evaluate extra line data
	$flag_trsf = 0;
    } elsif ($flag_line) { # evaluate line data row
	$nline++;
	$busfr[$nline] = assign($_,0,4,1);
	if (substr($_,6,1) =~ /C/) {
	    $flag_trsf = 1;
	} else {
	    $flag_trsf = 0;
	}
	$busto[$nline] = assign($_,8,4,1);
	$rest[$nline] = assign($_,17,6,0)/100;
	$reat[$nline] = assign($_,23,6,0)/100;	    
	$sbas[$nline] = assign($_,68,5,100);	    
	$susc[$nline] = assign($_,29,6,0)/1000/$sbas[$nline];
	$tfas[$nline] = assign($_,35,5,1000);
	if ($tfas[$nline] > 100) {$tfas[$nline] = $tfas[$nline]/1000;}
	$tfmi[$nline] = assign($_,40,5,0)/1000;
	$tfma[$nline] = assign($_,45,5,0)/1000;
	$phsf[$nline] = 3.141592654*assign($_,50,5,0)/18000;
	$nbci[$nline] = assign($_,55,5,0);
	$cano[$nline] = assign($_,60,4,0)/$sbas[$nline];
	$caem[$nline] = assign($_,64,4,0)/$sbas[$nline];	    
	$verbose && printf("Found Line %4d: %4d -> %4d\n",$nline+1,$busfr[$nline],$busto[$nline]);
    } elsif ($flag_area) { # evaluate area data row
	$_ = $_ . " " x 66;
	$narea++;
	$areaidx[$narea] = substr($_,2,2);
	$areabus[$narea] = substr($_,4,4);
	$areaexp[$narea] = assign($_,8,6,0)/$pbas;
	$areaint[$narea] = assign($_,14,5,0)/$pbas;
	$areaname[$narea] = substr($_,19,34);
	$areaload[$narea] = assign($_,55,5,0)/$pbas;
	$arealoss[$narea] = assign($_,60,5,0)/$pbas;	
    } else {
	$verbose && print "Warning: Line $n does not seem properly formed and will be ignored.\n";
    }
}

# -----------------------------------------------------------------------
# close input data file
# -----------------------------------------------------------------------
close(IN) || die "cannot close $ARGV[0]: $!\n";

# -----------------------------------------------------------------------
# open output data file
# -----------------------------------------------------------------------
print "Writing PSAT file \"$ARGV[1]\"...\n";
carret();
open(OUT,">$ARGV[1]") || die "cannot open $ARGV[1]: $!\n";

# -----------------------------------------------------------------------
# write output data file
# -----------------------------------------------------------------------
print OUT "% File generated by PSAT from PSAP data file.\n";
print OUT "% "."-" x 78 . "\n";
print OUT "% Author:   Federico Milano\n";
print OUT "% E-mail:   fmilano\@thunderbox.uwaterloo.ca\n";
print OUT "% Web-site: http://thunderbox.uwaterloo.ca/~fmilano\n";
print OUT "% "."-" x 78 . "\n";
print OUT "% $title1\n";
print OUT "% $title2\n\n";

# -----------------------------------------------------------------------
# write Bus.con
# -----------------------------------------------------------------------
$format = "%4d %8.2f %8.5f %8.5f %2d 1";
$nbus >= 0 && print OUT "Bus.con = [ ...\n";
for ($i = 0; $i <= $nbus-1; $i++) {
    printf OUT "$format;\n",$busidx[$i],$kvb[$i],$ein[$i],$ang[$i],
    $kae[$i];
}
$i = $nbus;
$nbus >= 0 && printf OUT "$format];\n\n", $busidx[$i], $kvb[$i], 
    $ein[$i], $ang[$i], $kae[$i];

# -----------------------------------------------------------------------
# write SW.con
# -----------------------------------------------------------------------
$nsw >= 0 && print OUT "SW.con = [ ...\n";
$format = "%4d $pbas %8.2f " . "%8.5f " x 4 . "1.1 0.9 %8.5f 1";
for ($i = 0; $i <= $nsw-1; $i++) {
    $h = $idxsw[$i];
    printf OUT "$format;\n", $busidx[$h],$kvb[$h],$ein[$h],$ang[$h],
    $qma[$h],$qmi[$h],$pag[$h];
}
$h = $idxsw[$nsw];
$nsw >= 0 && printf OUT "$format];\n\n",$busidx[$h],$kvb[$h],$ein[$h],
    $ang[$h],$qma[$h],$qmi[$h],$pag[$h];

# -----------------------------------------------------------------------
# write PV.con
# -----------------------------------------------------------------------
$npv >= 0 && print OUT "PV.con = [ ...\n";
$format = "%4d $pbas %8.2f " . "%8.5f " x 4 . "1.1 0.9 1";
for ($i = 0; $i <= $npv-1; $i++) {
    $h = $idxpv[$i];
    printf OUT "$format;\n", $busidx[$h],$kvb[$h],$pag[$h],$ein[$h],
    $qma[$h],$qmi[$h];
}
$h = $idxpv[$npv];
$npv >= 0 && printf OUT "$format];\n\n",$busidx[$h],$kvb[$h],$pag[$h],
    $ein[$h],$qma[$h],$qmi[$h];

# -----------------------------------------------------------------------
# write PQ.con
# -----------------------------------------------------------------------
$npq >= 0 && print OUT "PQ.con = [ ...\n";
$format = "%4d $pbas %8.2f %8.5f %8.5f 1.1 0.9 1";
for ($i = 0; $i <= $npq-1; $i++) {
    $h = $idxpq[$i];
    printf OUT "$format;\n", $busidx[$h],$kvb[$h],$pac[$h],$prc[$h];
}
$h = $idxpq[$npq];
$npq >= 0 && printf OUT "$format];\n\n",$busidx[$h],$kvb[$h],$pac[$h],
    $prc[$h];

# -----------------------------------------------------------------------
# write Shunt.con
# -----------------------------------------------------------------------
$nsh >= 0 && print OUT "Shunt.con = [ ...\n";
$format = "%4d $pbas %8.2f 60 0.00 %8.5f";
for ($i = 0; $i <= $nsh-1; $i++) {
    $h = $idxsh[$i];
    printf OUT "$format;\n", $busidx[$h],$kvb[$h],$qsh[$h];
}
$h = $idxsh[$nsh];
$nsh >= 0 && printf OUT "$format];\n\n",$busidx[$h],$kvb[$h],$qsh[$h];

# -----------------------------------------------------------------------
# write Line.con
# -----------------------------------------------------------------------
$nline >= 0 && print OUT "Line.con = [ ...\n";
$format = "%4d %4d %8.2f %8.2f 60 0 %5.2f " . "%8.5f " x 5 . "0 %8.3f %8.3f";
for ($i = 0; $i <= $nline-1; $i++) {
    $k = $kvbase{$busfr[$i]}/$kvbase{$busto[$i]};
    if ($k == 1) {$k = 0;}
    printf OUT "$format;\n", $busfr[$i],$busto[$i],$sbas[$i],
    $kvbase{$busfr[$i]},$k,$rest[$i],$reat[$i],$susc[$i],$tfas[$i],
    $phsf[$i],$cano[$i],$caem[$i];
}
$i = $nline;
if ($nline >= 0) {
    $k = $kvbase{$busfr[$i]}/$kvbase{$busto[$i]};
    if ($k == 1) {$k = 0;}
    printf OUT "$format];\n\n",$busfr[$i],$busto[$i],
    $sbas[$i],$kvbase{$busfr[$i]},$k,$rest[$i],$reat[$i],$susc[$i],
    $tfas[$i],$phsf[$i],$cano[$i],$caem[$i];
}

# -----------------------------------------------------------------------
# write bus names
# -----------------------------------------------------------------------
$nbus >= 0 && print OUT "Bus.names = { ...\n";
$h = ($nbus+1) % 5;
if ($h == 0) {$h = 5;}
if (($nbus+1) > 5) {
    for ($i = 0; $i <= $nbus-$h; $i+=5) {
	print OUT "  '$busname[$i]'; '$busname[$i+1]'; " . 
	    "'$busname[$i+2]'; '$busname[$i+3]'; '$busname[$i+4]';\n";
    }
}
print OUT "  ";
for ($i = $nbus-$h+1; $i <= $nbus-1; $i++) {
    print OUT "'$busname[$i]'; ";
}
print OUT "'$busname[$nbus]'};\n\n";

# -----------------------------------------------------------------------
# close output data file
# -----------------------------------------------------------------------
close(OUT) || die "cannot close $ARGV[1]: $!\n";
print "Conversion completed.\n";



# -----------------------------------------------------------------------
# function for formatting data and/or assigning default values
# -----------------------------------------------------------------------
sub assign {
    my $param;
    $param = substr($_[0],$_[1],$_[2]);
    $param =~ s/\s*//g;
    unless ($param) {$param = "0";}
    #$param =~ s/^0*\.0*//;
    unless ($param =~ /[1-9]/) {$param = $_[3];}
    return $param;
}

# -----------------------------------------------------------------------
# function for formatting data and/or assigning default values
# -----------------------------------------------------------------------
sub deblank {
    my $name = $_[0];
    $name =~ s/( *)$//;
    return $name;
}

# -----------------------------------------------------------------------
# function for writing a separator
# -----------------------------------------------------------------------
sub carret {
    $verbose && print "-" x 50 . "\n";
}
